package com.lvmama.java.rhino.spark.core.zookeeper;

import com.lvmama.java.rhino.spark.core.ICallback;
import com.lvmama.java.rhino.spark.utils.ZookeeperUtils;

/**
 * Zookeeper事件监听器 
 * @author wxliyong
 */
public class ZNodeMonitor implements ICallback {

	private String znode;

	private ZNodeListener listener;
	
	private boolean isOver = false;

	public ZNodeMonitor(String znode, ZNodeListener listener) {
		this.znode = znode;
		this.listener = listener;
	}

	public void start() {
		ZookeeperUtils.getInstance().registerWatcher(znode, this);
	}
	
	public boolean isOver() {
		return isOver;
	}
	
	@Override
	public void call(Object obj) {
		if(obj == null || !(obj instanceof ZNodeEvent)) {
			return;
		}
		ZNodeEvent zNodeEvent = (ZNodeEvent)obj;
		if(ZNodeEvent.EventStatus.EXPIRED.equals(zNodeEvent.getStatus())) {
			listener.closing(-1);
			isOver = true;
			return;
		}
		listener.process(zNodeEvent);
		ZookeeperUtils.getInstance().registerWatcher(znode, this);
	}
}